package com.zyn.rsgl.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zyn.rsgl.mapper.ScheduleDetailMapper;
import com.zyn.rsgl.mapper.ScheduleMapper;
import com.zyn.rsgl.mapper.ScheduleUserMapper;
import com.zyn.rsgl.pojo.ScheduleDetail;
import com.zyn.rsgl.pojo.ScheduleUser;
import com.zyn.rsgl.service.ScheduleDetailService;
import com.zyn.rsgl.utils.commonResult.R;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.util.List;

@Service
public class ScheduleDetailServiceImpl extends ServiceImpl<ScheduleDetailMapper, ScheduleDetail> implements ScheduleDetailService {
    @Resource
    ScheduleUserMapper scheduleUserMapper;
    @Resource
    ScheduleDetailMapper scheduleDetailMapper;
    @Override
    public R listPage(Integer pageNum, Integer pageSize, String name) {
        QueryWrapper<ScheduleDetail> queryWrapper = new QueryWrapper<>();

        Page<ScheduleDetail> page = PageHelper.startPage(pageNum, pageSize);
        List<ScheduleDetail> list = this.list(queryWrapper);
        if (list != null) {
            return R.ok(list, page.getTotal());
        }
        return R.fail("查询失败");
    }

    @Override
    public R getUserSchedule(String userId, String date) {
        // 解析日期
        LocalDate localDate = LocalDate.parse(date);

        // 获取用户绑定的排班模板ID
        QueryWrapper<ScheduleUser> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("user_id", userId);
        ScheduleUser scheduleUser = scheduleUserMapper.selectOne(userQueryWrapper);
        if (scheduleUser == null) {
            return R.fail("用户未绑定排班模板");
        }

        // 获取当天的星期几
        DayOfWeek dayOfWeek = localDate.getDayOfWeek();
        String dayOfWeekStr = getChineseDayOfWeek(dayOfWeek);

        // 使用 ScheduleDetailMapper 查询
        ScheduleDetail scheduleDetail = scheduleDetailMapper.getScheduleDetailByDayOfWeek(userId, dayOfWeekStr);
        if (scheduleDetail == null) {
            return R.fail("当天没有排班信息");
        }

        return R.ok(scheduleDetail);
    }

    public static String getChineseDayOfWeek(DayOfWeek dayOfWeek) {
        switch (dayOfWeek) {
            case MONDAY:
                return "星期一";
            case TUESDAY:
                return "星期二";
            case WEDNESDAY:
                return "星期三";
            case THURSDAY:
                return "星期四";
            case FRIDAY:
                return "星期五";
            case SATURDAY:
                return "星期六";
            case SUNDAY:
                return "星期日";
            default:
                return "未知";
        }
    }
}
